package com.software.loginregister.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.software.loginregister.R;
import com.software.loginregister.api.WorksApi;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.Works;
import com.software.loginregister.entity.vo.CookingStepVO;
import com.software.loginregister.entity.vo.IngredientDTO;
import com.software.loginregister.entity.vo.PublishWorksDTO;
import com.software.loginregister.entity.vo.WorksDTO;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PublishWorkActivity extends AppCompatActivity {
    private static final String TAG = "PublishWorkActivity";
    private LinearLayout stepsContainer;
    private int stepCount = 0;
    private ImageView workPhotoView;
    private static final int PICK_WORK_IMAGE = 1;
    private static final int PICK_STEP_IMAGE = 2;
    private int currentStepForImage = -1;
    private WorksApi worksApi;
    private SharedPreferences sharedPreferences;
    private ProgressDialog progressDialog;
    private Uri mainPhotoUri;
    private List<Uri> stepPhotoUris = new ArrayList<>();
    private LinearLayout ingredientsContainer;
    private int ingredientCount = 0;
    private static final int MAX_IMAGE_SIZE = 1024 * 1024; // 1MB
    private static final int COMPRESSION_QUALITY = 80; // 压缩质量
    private boolean isSavingDraft = false;
    private List<String> selectedPhotos = new ArrayList<>();
    private Integer draftId;
    private Spinner difficultySpinner;
    private String[] difficultyLevels = {"简单", "中等", "困难"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_work);

        worksApi = RetrofitClient.getInstance().create(WorksApi.class);
        sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在发布...");

        // 获取传递的草稿ID
        draftId = getIntent().getIntExtra("draft_id", -1);
        if (draftId != -1) {
            // 如果有草稿ID，加载草稿数据
            loadDraft(draftId);
        }
        // 初始化难度选择器
        difficultySpinner = findViewById(R.id.spinner_cooking_difficulty);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                difficultyLevels
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        difficultySpinner.setAdapter(adapter);

        initViews();
        setupListeners();
        initIngredientsView();
    }

    // 添加加载草稿的方法
    private void loadDraft(int draftId) {
        showProgressDialog();
        progressDialog.setMessage("正在加载草稿...");

        // 从SharedPreferences获取用户ID
        int userId = sharedPreferences.getInt("user_id", -1);
        if (userId == -1) {
            Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
            dismissProgressDialog();
            return;
        }

        worksApi.getDraftDetail(draftId, userId).enqueue(new Callback<Result<Works>>() {
            @Override
            public void onResponse(Call<Result<Works>> call, Response<Result<Works>> response) {
                dismissProgressDialog();
                if (response.isSuccessful() && response.body() != null && response.body().getCode() == 1) {
                    Works draft = response.body().getData();
                    if (draft != null) {
                        populateDraftData(draft);
                    }
                } else {
                    String errorMsg = response.body() != null ? response.body().getMsg() : "加载草稿失败";
                    Toast.makeText(PublishWorkActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result<Works>> call, Throwable t) {
                dismissProgressDialog();
                Toast.makeText(PublishWorkActivity.this,
                        "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                Log.e(TAG, "加载草稿失败", t);
            }
        });
    }

    // 添加填充草稿数据的方法
    private void populateDraftData(Works draft) {
        // 填充标题和描述
        ((EditText) findViewById(R.id.edt_publish_work_title)).setText(draft.getWorksName());
        ((EditText) findViewById(R.id.edt_publish_work_description)).setText(draft.getDescription());

        // 加载主图片
        if (!TextUtils.isEmpty(draft.getPhotoUrl())) {
            Glide.with(this)
                    .load(draft.getPhotoUrl())
                    .into(workPhotoView);
        }

        // 清空并重新添加食材
        clearIngredients();
        if (!TextUtils.isEmpty(draft.getMainIngredients())) {
            try {
                // 假设ingredients是JSON格式的字符串，需要解析
                List<IngredientDTO> ingredients = new Gson().fromJson(
                        draft.getMainIngredients(),
                        new com.google.gson.reflect.TypeToken<List<IngredientDTO>>() {
                        }.getType()
                );

                if (ingredients != null) {
                    for (IngredientDTO ingredient : ingredients) {
                        addNewIngredient();
                        View ingredientView = ingredientsContainer.getChildAt(ingredientsContainer.getChildCount() - 1);
                        ((EditText) ingredientView.findViewById(R.id.edt_ingredient_name))
                                .setText(ingredient.getIngredientName());
                        ((EditText) ingredientView.findViewById(R.id.edt_ingredient_amount))
                                .setText(String.valueOf(ingredient.getAmount()));
                        ((EditText) ingredientView.findViewById(R.id.edt_ingredient_unit))
                                .setText(ingredient.getUnit());
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "解析食材数据失败", e);
                Toast.makeText(this, "食材数据格式错误", Toast.LENGTH_SHORT).show();
            }
        }

        // 清空并重新添加步骤
        stepsContainer.removeAllViews();
        stepCount = 0;
        if (!TextUtils.isEmpty(draft.getSteps())) {
            try {
                // 假设steps是JSON格式的字符串，需要解析
                List<CookingStepVO> steps = new Gson().fromJson(
                        draft.getSteps(),
                        new com.google.gson.reflect.TypeToken<List<CookingStepVO>>() {
                        }.getType()
                );

                if (steps != null) {
                    for (CookingStepVO step : steps) {
                        addNewStep();
                        View stepView = stepsContainer.getChildAt(stepCount - 1);
                        ((EditText) stepView.findViewById(R.id.edt_publish_work_step_description))
                                .setText(step.getDescription());

                        // 加载步骤图片
                        String photoUrl = step.getPhotoUrl(); // 假设CookingStepVO中的图片URL字段名为photoUrl
                        if (!TextUtils.isEmpty(photoUrl)) {
                            ImageView stepPhotoView = stepView.findViewById(R.id.btn_publish_work_add_photo);
                            Glide.with(this)
                                    .load(photoUrl)
                                    .into(stepPhotoView);
                        }
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "解析步骤数据失败", e);
                Toast.makeText(this, "步骤数据格式错误", Toast.LENGTH_SHORT).show();
            }
        }

        Toast.makeText(this, "草稿加载成功", Toast.LENGTH_SHORT).show();
    }

    // 添加图片压缩方法
    private File compressImage(Uri imageUri) {
        try {
            // 创建临时文件来存储压缩后的图片
            File outputDir = getCacheDir();
            File outputFile = File.createTempFile("compressed_", ".jpg", outputDir);

            // 获取原始图片的 Bitmap
            android.graphics.Bitmap originalBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);

            // 计算压缩比例
            int width = originalBitmap.getWidth();
            int height = originalBitmap.getHeight();
            float ratio = 1.0f;

            // 如果图片太大，计算压缩比例
            if (width > 2048 || height > 2048) {
                ratio = Math.min(2048f / width, 2048f / height);
                width = (int) (width * ratio);
                height = (int) (height * ratio);
            }

            // 创建压缩后的 Bitmap
            android.graphics.Bitmap compressedBitmap = android.graphics.Bitmap.createScaledBitmap(
                    originalBitmap, width, height, true);

            // 使用 JPEG 格式压缩图片
            java.io.FileOutputStream fos = new java.io.FileOutputStream(outputFile);
            compressedBitmap.compress(android.graphics.Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
            fos.flush();
            fos.close();

            // 释放 Bitmap 资源
            if (originalBitmap != null && !originalBitmap.isRecycled()) {
                originalBitmap.recycle();
            }
            if (compressedBitmap != null && !compressedBitmap.isRecycled()) {
                compressedBitmap.recycle();
            }

            // 检查压缩后的文件大小
            if (outputFile.length() > MAX_IMAGE_SIZE) {
                // 如果还是太大，继续压缩
                android.graphics.Bitmap recompressBitmap = android.graphics.BitmapFactory.decodeFile(outputFile.getAbsolutePath());
                fos = new java.io.FileOutputStream(outputFile);
                recompressBitmap.compress(android.graphics.Bitmap.CompressFormat.JPEG, 60, fos);
                fos.flush();
                fos.close();
                recompressBitmap.recycle();
            }

            return outputFile;
        } catch (Exception e) {
            Log.e(TAG, "压缩图片失败", e);
            return null;
        }
    }

    private void initIngredientsView() {
        ingredientsContainer = findViewById(R.id.ll_ingredients_container);

        // 添加食材按钮
        findViewById(R.id.btn_add_ingredient).setOnClickListener(v -> addNewIngredient());

        // 清空食材按钮
//        findViewById(R.id.btn_clear_ingredients).setOnClickListener(v -> clearIngredients());

        // 默认添加一个食材输入项
        addNewIngredient();
    }

    private void addNewIngredient() {
        ingredientCount++;
        Log.d(TAG, "添加新食材，当前食材数量：" + ingredientCount);

        View ingredientView = getLayoutInflater().inflate(R.layout.item_add_ingredient, null);
        TextView tvIngredientTitle = ingredientView.findViewById(R.id.tv_ingredient_title);
        tvIngredientTitle.setText("食材" + ingredientCount);

        ImageButton btnDeleteIngredient = ingredientView.findViewById(R.id.btn_delete_ingredient);
        btnDeleteIngredient.setOnClickListener(v -> {
            if (ingredientsContainer.getChildCount() > 1) {
                ingredientsContainer.removeView(ingredientView);
                updateIngredientNumbers();
            } else {
                Toast.makeText(this, "至少需要一个食材", Toast.LENGTH_SHORT).show();
            }
        });


        ingredientsContainer.addView(ingredientView);
        Log.d(TAG, "新食材添加完成，当前容器中食材数量：" + ingredientsContainer.getChildCount());
    }

    private void updateIngredientNumbers() {
        Log.d(TAG, "开始更新食材编号");
        ingredientCount = 0;
        for (int i = 0; i < ingredientsContainer.getChildCount(); i++) {
            View ingredientView = ingredientsContainer.getChildAt(i);
            TextView tvIngredientTitle = ingredientView.findViewById(R.id.tv_ingredient_title);
            ingredientCount++;
            tvIngredientTitle.setText("食材" + ingredientCount);
        }
        Log.d(TAG, "食材编号更新完成，当前食材总数：" + ingredientCount);
    }

    private void initViews() {
        stepsContainer = findViewById(R.id.ll_steps_container);
        workPhotoView = findViewById(R.id.iv_publish_work_photo);
        addNewStep();
    }

    private void setupListeners() {
        findViewById(R.id.btn_publish_work_back).setOnClickListener(v -> finish());
        findViewById(R.id.tv_publish_work).setOnClickListener(v -> {
            if (validateInput()) {
                publishWork();
            }
        });
        findViewById(R.id.btn_publish_work_add_step).setOnClickListener(v -> addNewStep());
        findViewById(R.id.btn_work_save_draft).setOnClickListener(v -> saveToDraft());
        workPhotoView.setOnClickListener(v -> pickImage(PICK_WORK_IMAGE));
    }

    private void addNewStep() {
        stepCount++;
        View stepView = getLayoutInflater().inflate(R.layout.item_publish_work_step, null);
        TextView tvStepTitle = stepView.findViewById(R.id.tv_publish_work_step_title);
        tvStepTitle.setText("第" + stepCount + "步");

        ImageView stepPhotoView = stepView.findViewById(R.id.btn_publish_work_add_photo);
        final int currentStep = stepCount;
        stepPhotoView.setOnClickListener(v -> {
            currentStepForImage = currentStep - 1;
            pickImage(PICK_STEP_IMAGE);
        });

        Button btnDeleteStep = stepView.findViewById(R.id.btn_delete_step);
        btnDeleteStep.setOnClickListener(v -> {
            if (stepsContainer.getChildCount() > 1) {
                stepsContainer.removeView(stepView);
                updateStepNumbers();
            } else {
                Toast.makeText(this, "至少需要保留一个步骤", Toast.LENGTH_SHORT).show();
            }
        });

        stepsContainer.addView(stepView);
    }

    private void updateStepNumbers() {
        stepCount = 0;
        for (int i = 0; i < stepsContainer.getChildCount(); i++) {
            View stepView = stepsContainer.getChildAt(i);
            TextView tvStepTitle = stepView.findViewById(R.id.tv_publish_work_step_title);
            stepCount++;
            tvStepTitle.setText("第" + stepCount + "步");
        }
    }

    private void pickImage(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            if (selectedImage != null) {
                switch (requestCode) {
                    case PICK_WORK_IMAGE:
                        mainPhotoUri = selectedImage;
                        workPhotoView.setImageURI(selectedImage);
                        break;

                    case PICK_STEP_IMAGE:
                        if (currentStepForImage >= 0) {
                            View stepView = stepsContainer.getChildAt(currentStepForImage);
                            if (stepView != null) {
                                ImageView stepPhotoView = stepView.findViewById(R.id.btn_publish_work_add_photo);
                                stepPhotoView.setImageURI(selectedImage);
                                while (stepPhotoUris.size() <= currentStepForImage) {
                                    stepPhotoUris.add(null);
                                }
                                stepPhotoUris.set(currentStepForImage, selectedImage);
                            }
                        }
                        break;
                }
            }
        }
    }

    private boolean validateInput() {
        // 验证标题和描述
        String title = ((EditText) findViewById(R.id.edt_publish_work_title)).getText().toString();
        String description = ((EditText) findViewById(R.id.edt_publish_work_description)).getText().toString();

        if (title.trim().isEmpty()) {
            Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (description.trim().isEmpty()) {
            Toast.makeText(this, "请输入作品描述", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 验证食材信息
        if (ingredientsContainer.getChildCount() == 0) {
            Toast.makeText(this, "请至少添加一种食材", Toast.LENGTH_SHORT).show();
            return false;
        }

        for (int i = 0; i < ingredientsContainer.getChildCount(); i++) {
            View ingredientView = ingredientsContainer.getChildAt(i);
            EditText edtName = ingredientView.findViewById(R.id.edt_ingredient_name);
            EditText edtAmount = ingredientView.findViewById(R.id.edt_ingredient_amount);
            EditText edtUnit = ingredientView.findViewById(R.id.edt_ingredient_unit);

            String name = edtName.getText().toString().trim();
            String amount = edtAmount.getText().toString().trim();
            String unit = edtUnit.getText().toString().trim();

            // 验证食材名称
            if (name.isEmpty()) {
                Toast.makeText(this, "请输入第" + (i + 1) + "个食材的名称", Toast.LENGTH_SHORT).show();
                edtName.requestFocus();
                return false;
            }

            // 验证食材数量
            if (amount.isEmpty()) {
                Toast.makeText(this, "请输入第" + (i + 1) + "个食材的数量", Toast.LENGTH_SHORT).show();
                edtAmount.requestFocus();
                return false;
            }

            // 验证数量是否为有效数字
            try {
                float amountValue = Float.parseFloat(amount);
                if (amountValue <= 0) {
                    Toast.makeText(this, "第" + (i + 1) + "个食材的数量必须大于0", Toast.LENGTH_SHORT).show();
                    edtAmount.requestFocus();
                    return false;
                }
            } catch (NumberFormatException e) {
                Toast.makeText(this, "第" + (i + 1) + "个食材的数量格式不正确", Toast.LENGTH_SHORT).show();
                edtAmount.requestFocus();
                return false;
            }

            // 验证单位
            if (unit.isEmpty()) {
                Toast.makeText(this, "请输入第" + (i + 1) + "个食材的单位（如：克、个、片等）", Toast.LENGTH_SHORT).show();
                edtUnit.requestFocus();
                return false;
            }

            // 验证食材名称长度
            if (name.length() > 10) {
                Toast.makeText(this, "第" + (i + 1) + "个食材的名称过长，请限制在10个字以内", Toast.LENGTH_SHORT).show();
                edtName.requestFocus();
                return false;
            }

            // 验证单位长度
            if (unit.length() > 2) {
                Toast.makeText(this, "第" + (i + 1) + "个食材的单位过长，请限制在2个字以内", Toast.LENGTH_SHORT).show();
                edtUnit.requestFocus();
                return false;
            }
        }

        // 验证作品图片
        if (workPhotoView.getDrawable() == null ||
                workPhotoView.getDrawable().getConstantState().equals(
                        getResources().getDrawable(R.drawable.ic_add_photo).getConstantState())) {
            Toast.makeText(this, "请添加作品图片", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 验证步骤信息
        for (int i = 0; i < stepsContainer.getChildCount(); i++) {
            View stepView = stepsContainer.getChildAt(i);
            EditText edtStepDescription = stepView.findViewById(R.id.edt_publish_work_step_description);
            ImageView ivStepPhoto = stepView.findViewById(R.id.btn_publish_work_add_photo);

            if (edtStepDescription.getText().toString().trim().isEmpty()) {
                Toast.makeText(this, "请填写第" + (i + 1) + "步的描述", Toast.LENGTH_SHORT).show();
                return false;
            }

            if (ivStepPhoto.getDrawable() == null ||
                    ivStepPhoto.getDrawable().getConstantState().equals(
                            getResources().getDrawable(R.drawable.ic_add_photo).getConstantState())) {
                Toast.makeText(this, "请添加第" + (i + 1) + "步的图片", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        // 验证烹饪时间
        String cookingTime = ((EditText) findViewById(R.id.edt_cooking_time)).getText().toString();
        if (cookingTime.trim().isEmpty()) {
            Toast.makeText(this, "请输入烹饪时长", Toast.LENGTH_SHORT).show();
            return false;
        }

        try {
            int time = Integer.parseInt(cookingTime);
            if (time <= 0) {
                Toast.makeText(this, "烹饪时长必须大于0", Toast.LENGTH_SHORT).show();
                return false;
            }
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的烹饪时长", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private void publishWork() {
        if (!validateInput()) {
            return;
        }

        isSavingDraft = false;
        showProgressDialog();

        try {
            // 获取实际的用户ID
            Long userId = SharedPreferencesUtil.getUserId(this);
            if (userId == null) {
                Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
                return;
            }

            PublishWorksDTO publishDTO = new PublishWorksDTO();
            publishDTO.setUserId(userId.intValue());

            // 获取烹饪时间
            EditText cookingTimeEdit = findViewById(R.id.edt_cooking_time);
            String cookingTime = cookingTimeEdit.getText().toString().trim();
            publishDTO.setCookingTime(Integer.parseInt(cookingTime));

            // 获取难度
            String selectedDifficulty = difficultySpinner.getSelectedItem().toString();
            publishDTO.setDifficulty(selectedDifficulty);

            // 压缩并准备主图片
            File compressedMainPhoto = compressImage(mainPhotoUri);
            if (compressedMainPhoto == null) {
                Toast.makeText(this, "主图片处理失败", Toast.LENGTH_SHORT).show();
                dismissProgressDialog();
                return;
            }

            RequestBody mainPhotoRequestBody = RequestBody.create(MediaType.parse("image/*"), compressedMainPhoto);
            MultipartBody.Part mainPhotoPart = MultipartBody.Part.createFormData(
                    "mainPhoto", compressedMainPhoto.getName(), mainPhotoRequestBody);

            // 压缩并准备步骤图片
            List<MultipartBody.Part> stepPhotoParts = new ArrayList<>();
            for (Uri stepPhotoUri : stepPhotoUris) {
                if (stepPhotoUri != null) {
                    File compressedStepPhoto = compressImage(stepPhotoUri);
                    if (compressedStepPhoto != null) {
                        RequestBody stepPhotoRequestBody = RequestBody.create(
                                MediaType.parse("image/*"), compressedStepPhoto);
                        MultipartBody.Part stepPhotoPart = MultipartBody.Part.createFormData(
                                "stepPhotos", compressedStepPhoto.getName(), stepPhotoRequestBody);
                        stepPhotoParts.add(stepPhotoPart);
                    }
                }
            }

            // 准备发布数据
            publishDTO.setWorksName(((EditText) findViewById(R.id.edt_publish_work_title)).getText().toString().trim());
            publishDTO.setDescription(((EditText) findViewById(R.id.edt_publish_work_description)).getText().toString().trim());

            // 收集食材信息
            List<IngredientDTO> ingredients = new ArrayList<>();
            for (int i = 0; i < ingredientsContainer.getChildCount(); i++) {
                View ingredientView = ingredientsContainer.getChildAt(i);
                EditText edtName = ingredientView.findViewById(R.id.edt_ingredient_name);
                EditText edtAmount = ingredientView.findViewById(R.id.edt_ingredient_amount);
                EditText edtUnit = ingredientView.findViewById(R.id.edt_ingredient_unit);

                String name = edtName.getText().toString().trim();
                String amount = edtAmount.getText().toString().trim();
                String unit = edtUnit.getText().toString().trim();

                IngredientDTO ingredient = new IngredientDTO();
                ingredient.setIngredientName(name);
                ingredient.setAmount(new BigDecimal(amount));
                ingredient.setUnit(unit);
                ingredients.add(ingredient);
            }

            // 设置食材列表
            publishDTO.setIngredients(ingredients);

            // 创建步骤列表
            List<CookingStepVO> steps = new ArrayList<>();
            for (int i = 0; i < stepsContainer.getChildCount(); i++) {
                View stepView = stepsContainer.getChildAt(i);
                EditText edtStepDescription = stepView.findViewById(R.id.edt_publish_work_step_description);

                CookingStepVO step = new CookingStepVO();
                step.setStepNumber(i + 1);
                step.setDescription(edtStepDescription.getText().toString().trim());
                steps.add(step);
            }
            publishDTO.setSteps(steps);

            // 将DTO转换为JSON
            String publishDTOJson = new Gson().toJson(publishDTO);
            Log.d(TAG, "发送的 DTO 数据: " + publishDTOJson);
            RequestBody publishDTOBody = RequestBody.create(
                    MediaType.parse("application/json; charset=utf-8"),
                    publishDTOJson);

            // 发送请求
            worksApi.publishWork(mainPhotoPart, stepPhotoParts, publishDTOBody)
                    .enqueue(new Callback<Result<Works>>() {
                        @Override
                        public void onResponse(Call<Result<Works>> call, Response<Result<Works>> response) {
                            dismissProgressDialog();
                            if (response.isSuccessful() && response.body() != null && response.body().getCode() == 1) {
                                Toast.makeText(PublishWorkActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                                finish();
                            } else {
                                String errorMsg = response.body() != null ? response.body().getMsg() : "发布失败";
                                Toast.makeText(PublishWorkActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<Result<Works>> call, Throwable t) {
                            dismissProgressDialog();
                            Toast.makeText(PublishWorkActivity.this,
                                    "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                            Log.e(TAG, "网络请求失败", t);
                        }
                    });

        } catch (Exception e) {
            dismissProgressDialog();
            Toast.makeText(this, "发布失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e(TAG, "发布过程出现异常", e);
        }
    }

    private void saveToDraft() {
        if (!validateDraft()) {
            return;
        }
        isSavingDraft = true;
        saveDraft();
    }

    private WorksDTO prepareWorksData() {
        WorksDTO worksDTO = new WorksDTO();
        // 从 SharedPreferences 获取用户ID
        int userId = sharedPreferences.getInt("user_id", -1);
        if (userId == -1) {
            Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
            return null;
        }
        worksDTO.setUserId(userId);
        worksDTO.setWorksName(((EditText) findViewById(R.id.edt_publish_work_title)).getText().toString().trim());
        worksDTO.setDescription(((EditText) findViewById(R.id.edt_publish_work_description)).getText().toString().trim());
        worksDTO.setDifficulty("简单");

        // 收集食材信息
        List<IngredientDTO> ingredients = new ArrayList<>();
        for (int i = 0; i < ingredientsContainer.getChildCount(); i++) {
            View ingredientView = ingredientsContainer.getChildAt(i);
            EditText edtName = ingredientView.findViewById(R.id.edt_ingredient_name);
            EditText edtAmount = ingredientView.findViewById(R.id.edt_ingredient_amount);
            EditText edtUnit = ingredientView.findViewById(R.id.edt_ingredient_unit);

            String name = edtName.getText().toString().trim();
            String amount = edtAmount.getText().toString().trim();
            String unit = edtUnit.getText().toString().trim();

            if (!TextUtils.isEmpty(name)) {
                IngredientDTO ingredient = new IngredientDTO();
                ingredient.setIngredientName(name);
                try {
                    ingredient.setAmount(new BigDecimal(amount));
                } catch (NumberFormatException e) {
                    ingredient.setAmount(BigDecimal.ZERO);
                }
                ingredient.setUnit(unit);
                ingredients.add(ingredient);
            }
        }
        worksDTO.setIngredients(ingredients.toString());

        return worksDTO;
    }

    private void saveDraft() {
        // 准备作品数据
        WorksDTO worksDTO = prepareWorksData();
        showProgressDialog();

        if (hasPhotos()) {  // 如果有图片
            try {
                // 准备主图片
                MultipartBody.Part mainPhotoPart = null;
                if (mainPhotoUri != null) {
                    File compressedMainPhoto = compressImage(mainPhotoUri);
                    if (compressedMainPhoto != null && compressedMainPhoto.exists()) {
                        RequestBody mainPhotoRequestBody = RequestBody.create(MediaType.parse("image/*"), compressedMainPhoto);
                        mainPhotoPart = MultipartBody.Part.createFormData("mainPhoto", compressedMainPhoto.getName(), mainPhotoRequestBody);
                    }
                }

                // 准备步骤图片
                List<MultipartBody.Part> stepPhotoParts = new ArrayList<>();
                if (!stepPhotoUris.isEmpty()) {
                    for (Uri stepPhotoUri : stepPhotoUris) {
                        if (stepPhotoUri != null) {
                            File compressedStepPhoto = compressImage(stepPhotoUri);
                            if (compressedStepPhoto != null && compressedStepPhoto.exists()) {
                                RequestBody stepPhotoRequestBody = RequestBody.create(MediaType.parse("image/*"), compressedStepPhoto);
                                MultipartBody.Part stepPhotoPart = MultipartBody.Part.createFormData(
                                        "stepPhotos", compressedStepPhoto.getName(), stepPhotoRequestBody);
                                stepPhotoParts.add(stepPhotoPart);
                            }
                        }
                    }
                }

                // 将作品数据转换为JSON字符串，然后创建RequestBody
                String worksJson = new Gson().toJson(worksDTO);
                RequestBody publishDTOBody = RequestBody.create(
                        MediaType.parse("application/json; charset=utf-8"),
                        worksJson
                );

                // 调用带图片的保存草稿API
                worksApi.saveDraft(mainPhotoPart, stepPhotoParts, publishDTOBody)
                        .enqueue(new Callback<Result<Works>>() {
                            @Override
                            public void onResponse(Call<Result<Works>> call, Response<Result<Works>> response) {
                                dismissProgressDialog();
                                handleDraftResponse(response);
                            }

                            @Override
                            public void onFailure(Call<Result<Works>> call, Throwable t) {
                                dismissProgressDialog();
                                handleDraftError(t);
                            }
                        });
            } catch (Exception e) {
                dismissProgressDialog();
                Toast.makeText(this, "保存草稿失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                Log.e(TAG, "保存草稿失败", e);
            }
        } else {  // 如果没有图片
            // 将作品数据转换为JSON字符串，然后创建RequestBody
            String worksJson = new Gson().toJson(worksDTO);
            RequestBody publishDTOBody = RequestBody.create(
                    MediaType.parse("application/json; charset=utf-8"),
                    worksJson
            );

            // 调用不带图片的保存草稿API
            worksApi.saveDraftWithoutPhotos(publishDTOBody)
                    .enqueue(new Callback<Result<Works>>() {
                        @Override
                        public void onResponse(Call<Result<Works>> call, Response<Result<Works>> response) {
                            dismissProgressDialog();
                            handleDraftResponse(response);
                        }

                        @Override
                        public void onFailure(Call<Result<Works>> call, Throwable t) {
                            dismissProgressDialog();
                            handleDraftError(t);
                        }
                    });
        }
    }

    private boolean hasPhotos() {
        return mainPhotoUri != null || !stepPhotoUris.isEmpty();
    }

    private MultipartBody.Part[] preparePhotosParts() {
        List<MultipartBody.Part> parts = new ArrayList<>();

        // 添加主图片
        if (mainPhotoUri != null) {
            File compressedMainPhoto = compressImage(mainPhotoUri);
            if (compressedMainPhoto != null) {
                RequestBody mainPhotoRequestBody = RequestBody.create(MediaType.parse("image/*"), compressedMainPhoto);
                parts.add(MultipartBody.Part.createFormData("mainPhoto", compressedMainPhoto.getName(), mainPhotoRequestBody));
            }
        }

        // 添加步骤图片
        for (Uri stepPhotoUri : stepPhotoUris) {
            if (stepPhotoUri != null) {
                File compressedStepPhoto = compressImage(stepPhotoUri);
                if (compressedStepPhoto != null) {
                    RequestBody stepPhotoRequestBody = RequestBody.create(MediaType.parse("image/*"), compressedStepPhoto);
                    parts.add(MultipartBody.Part.createFormData("stepPhotos", compressedStepPhoto.getName(), stepPhotoRequestBody));
                }
            }
        }

        return parts.toArray(new MultipartBody.Part[0]);
    }

    private RequestBody convertWorksToRequestBody(WorksDTO worksDTO) {
        // 将WorksDTO转换为RequestBody
        String worksJson = new Gson().toJson(worksDTO);
        return RequestBody.create(MediaType.parse("application/json"), worksJson);
    }

    private boolean validateDraft() {
        // 草稿的验证规则更宽松，只需要标题不为空
        String title = ((EditText) findViewById(R.id.edt_publish_work_title)).getText().toString();
        if (title.trim().isEmpty()) {
            Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void handleDraftResponse(Response<Result<Works>> response) {
        if (response.isSuccessful() && response.body() != null && response.body().getCode() == 1) {
            Toast.makeText(PublishWorkActivity.this, "已保存到草稿箱", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            String errorMsg = response.body() != null ? response.body().getMsg() : "保存草稿失败";
            Toast.makeText(PublishWorkActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
        }
    }

    private void handleDraftError(Throwable t) {
        Toast.makeText(PublishWorkActivity.this,
                "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
        Log.e(TAG, "保存草稿失败", t);
    }

    interface ImageUploadCallback {
        void onSuccess(Integer mainPhotoId, List<Integer> stepPhotoIds);

        void onFailure(String error);
    }


    private void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
        }
        progressDialog.setMessage(isSavingDraft ? "正在保存草稿..." : "正在发布...");
        progressDialog.setCancelable(false);
        if (!isFinishing() && !progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissProgressDialog();
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismissProgressDialog();
    }

    private void clearIngredients() {
        ingredientsContainer.removeAllViews();
        ingredientCount = 0;
        addNewIngredient();
    }
}
